package logic

import (
	"context"
	"gitee.com/Cauchy_AQ/vxopen/model/mongodb"
	"gitee.com/Cauchy_AQ/vxopen/pkg/jwt"
	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/internal/errors"
	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/internal/svc"
	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/transform"
	"gitee.com/Cauchy_AQ/vxopen/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type AuthorizationLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAuthorizationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AuthorizationLogic {
	return &AuthorizationLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AuthorizationLogic) Authorization(in *transform.UserOptReq) (*transform.UserOptResp, error) {
	// 1. 校验验证码是否正确
	if !VerifyCaptcha(in.Key, in.Code) {
		return nil, errors.ErrorVerifyCaptcha
	}
	// 2. 检查用户是否存在，并校验密码
	mongoClient := mongodb.GetMongoInstance(l.svcCtx.Config.ModelConfig)
	user, err := mongoClient.UserCol.FindOneByMobile(context.Background(), in.Mobile)
	if err != nil {
		return nil, err
	}
	if user == nil {
		return nil, errors.ErrorUserNotExist
	}

	if !utils.CheckPassword(in.Passwd, user.Password) {
		return nil, errors.ErrorPassword
	}

	// 3. 创建 Token
	aToken, rToken, err := jwt.GenToken(user.Name, user.Mobile, user.OpenID, user.Role.Name)
	if err != nil {
		return nil, err
	}
	return &transform.UserOptResp{
		AccessToken:  aToken,
		RefreshToken: rToken,
	}, nil
}
